<template>
  <div class="btnNum">
    <el-card style="width: 98%; margin: 0 auto; margin-top: 10px">
      <div>
        <el-badge :value="form.foods.length" class="item" color="green">
          <el-button type="primary" @click="addfoods">选择食材</el-button>
        </el-badge>
      </div>

      <el-table v-if="isShow" :data="form.foods" style="width: 100%">
        <el-table-column prop="id" label="序号" />
        <el-table-column prop="name" label="物料名称" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="supplierName" label="供应商" />
        <el-table-column prop="wholePrice" label="批发价" />
        <el-table-column prop="sellPrice" label="零售价" />
        <el-table-column prop="purchasePrice" label="采购价" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button type="text" size="small" @click="del(scope.row.id)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="text">
        合计：采购品种数{{ form.foods.length }}，采购总成本：{{ calculateTotalCost }}元
      </div>

      <el-form :model="form" label-width="auto" style="max-width: 600px; margin-bottom: 50px">
        <el-form-item label="请输入备注:">
          <el-input v-model="form.remarks" type="textarea" style="width: 250px" clearable />
        </el-form-item>
        <el-form-item />
        <el-form-item label="期望到货日期:">
          <el-date-picker
            v-model="form.receiveTime"
            type="datetime"
            placeholder="请选择"
            clearable
          />
        </el-form-item>
      </el-form>
    </el-card>

    <div class="btns">
      <el-button @click="back">返回</el-button>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="primary" @click="add">保存并提交</el-button>
    </div>

    <!-- 添加食材 -->
    <addFood
      v-if="dialogVisible"
      :selectList="selectList"
      @close="handelClose"
      @confirm="handelConfirm"
    />
  </div>
</template>

<script setup lang="ts">
import { ref } from "vue";
import addFood from "@/components/logistics/purchaseAdd.vue";
import { purchaseAdd } from "@/api/logistics/purchase/purchase";
import { purchaseAddParams } from "@/api/logistics/purchase/type";
import dayjs from "dayjs";
import { useRouter } from "vue-router";
const router = useRouter();

const dialogVisible = ref(false);

let form = reactive<purchaseAddParams>({
  remarks: "",
  receiveTime: "",
  foods: [],
});

//表格选中数据
let selectList = ref<any[]>([]);
// 表格数据
const isShow = ref(false);
const handelConfirm = (data: any) => {
  dialogVisible.value = false;

  let arr = Array.from(new Set(data.map((item: any) => item.id))).map((id) =>
    data.find((item: any) => item.id === id)
  );
  form.foods = arr;
  selectList.value = arr;
  isShow.value = true;
};

// 采购成本
const calculateTotalCost = computed(() => {
  return form.foods.reduce((total, item: any) => total + item.purchasePrice, 0);
});

// 保存
const save = () => {
  router.push("/logistics/purchase");
  localStorage.setItem("form", JSON.stringify(form));
};

// 添加
const add = async () => {
  // 时间格式化
  form.receiveTime = dayjs(form.receiveTime).format("YYYY-MM-DD HH:mm");

  await purchaseAdd(form);
  // console.log('添加', res);
  ElMessage.success("添加成功");
  localStorage.removeItem("form");
  router.push("/logistics/purchase");
};

// 删除
const del = (id: number) => {
  form.foods = form.foods.filter((item) => item.id !== id);
};

// 返回
const back = () => {
  router.push("/logistics/purchase");
};

// 选择食材
const addfoods = () => {
  console.log(111);

  dialogVisible.value = true;
};

// 关闭弹框
const handelClose = () => {
  dialogVisible.value = false;
};

onMounted(() => {
  const storedForm = localStorage.getItem("form");
  if (storedForm) {
    Object.assign(form, JSON.parse(storedForm));
    isShow.value = true;
    // console.log(form);
  }
});
</script>

<style lang="less" scoped>
.btnNum {
  margin: 10px 0 10px 10px;

  .text {
    font-size: 14px;
    margin: 10px 0 30px 0;
  }

  .btns {
    display: flex;
    justify-content: center;
    margin-top: 40px;
  }
}
</style>
